/*
新增读取引脚功能
新增控制开关功能
*/
#include <ModbusRTUSlave.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// size of data which will be read and written
#define DATA_SIZE 100
// data array which will be read and written
u16 _D[DATA_SIZE];

// address (kind of name) of above data, may be anything
#define VIRTUAL_ADDRESS 0x7000

#define OUR_ID_AS_A_SLAVE 2
#define PIN_CONNECTED_TO_BOTH_DE_AND_RE 3

ModbusRTUSlave rtu(OUR_ID_AS_A_SLAVE, &Serial1, PIN_CONNECTED_TO_BOTH_DE_AND_RE);

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

int boiler_pin = 8;

int op_switchs[] = {A0, A1, A2, A3, A4, A5, A6, A7};
int relay_switchs[] = {A8, A9, A10, A11, A12, A13, A14, A15};

//boiler turn on
void turn_on_boiler()
{
  digitalWrite(boiler_pin, HIGH);
}
//boiler turn off
void turn_off_boiler()
{
  digitalWrite(boiler_pin, LOW);
}

void process_boiler()
{
  int temp = _D[0] / 100;
  if (100 == _D[1]) {
    turn_on_boiler();
    return;
  }
  
  if (temp < (_D[1] - 10)) {
    turn_on_boiler();
  }
  if (temp > _D[1]) {
    turn_off_boiler();
  }
  
}

//void process_relay()
//{
//  for (int i=10; i<=17; i++) {
//    if (_D[i] > 0 && _D[i-8] == 0)//让继电器开，判断传感器是否检测到物品
//      digitalWrite(relay_switchs[i-10], HIGH);
//    else
//    {
//      digitalWrite(relay_switchs[i-10], LOW);
//      _D[i] = 0;
//    }
//    
//  }
//}

void setup()
{ 
  rtu.addWordArea(VIRTUAL_ADDRESS, _D, DATA_SIZE);
  rtu.begin(19200, SERIAL_8N2);

  sensors.begin();

  Serial.begin(9600); // not needed, for logging purpose only

  

  // set some value in data array to test if master can read and modify it
  _D[0] = 0;

  //温度寄存器
  _D[1] = 0;

  pinMode(boiler_pin, OUTPUT);
//  for (int i=0; i<sizeof(op_switchs); i++) {
//    pinMode(op_switchs[i], INPUT);
//  }
//  for (int i=0; i<sizeof(relay_switchs); i++) {
//    pinMode(relay_switchs[i], OUTPUT);
//  }

  
  turn_off_boiler();
}

//_D
/*
0 当前温度
1 设置温度
2-9 接近开关状态（容器）
10-17 控制继电器
*/
void loop()
{
  // waiting for requests from master
  // reading and writing _D according to requests from master happens here
  rtu.process();

  sensors.requestTemperatures();
  _D[0] = (u16)(sensors.getTempCByIndex(0) * 100);

  process_boiler();
//  Serial.print("recv:");
//  Serial.println(_D[1]);
//  Serial.println(_D[0]);
  
  //A0 A1 A2 A3
//  int index = 2;
//  for (int i=0; i<sizeof(op_switchs); i++) {
//    _D[index] = digitalRead(op_switchs[i]);
//    index ++;
//  }

//  process_relay();
}
